/*
*  Copyright (c) 2001 Sun Microsystems, Inc.  All rights
*  reserved.
*
*  Redistribution and use in source and binary forms, with or without
*  modification, are permitted provided that the following conditions
*  are met:
*
*  1. Redistributions of source code must retain the above copyright
*  notice, this list of conditions and the following disclaimer.
*
*  2. Redistributions in binary form must reproduce the above copyright
*  notice, this list of conditions and the following disclaimer in
*  the documentation and/or other materials provided with the
*  distribution.
*
*  3. The end-user documentation included with the redistribution,
*  if any, must include the following acknowledgment:
*  "This product includes software developed by the
*  Sun Microsystems, Inc. for Project JXTA."
*  Alternately, this acknowledgment may appear in the software itself,
*  if and wherever such third-party acknowledgments normally appear.
*
*  4. The groups "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA"
*  must not be used to endorse or promote products derived from this
*  software without prior written permission. For written
*  permission, please contact Project JXTA at http://www.jxta.org.
*
*  5. Products derived from this software may not be called "JXTA",
*  nor may "JXTA" appear in their group, without prior written
*  permission of Sun.
*
*  THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
*  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
*  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
*  DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
*  ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
*  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
*  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
*  USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
*  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
*  OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
*  OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
*  SUCH DAMAGE.
*  ====================================================================
*
*  This software consists of voluntary contributions made by many
*  individuals on behalf of Project JXTA.  For more
*  information on Project JXTA, please see
*  <http://www.jxta.org/>.
*
*  This license is based on the BSD license adopted by the Apache Foundation.
*
*  $Id: ProxyHttp.java,v 1.2 2005/10/28 17:15:02 nano Exp $
*/

package net.jxta.myjxta.ui;

import net.jxta.myjxta.MyJXTA;
import net.jxta.myjxta.util.Constants;
import net.jxta.myjxta.util.Env;
import net.jxta.myjxta.util.Resources;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ResourceBundle;

/**
 *
 * @version $Id: ProxyHttp.java,v 1.2 2005/10/28 17:15:02 nano Exp $
 *
 * @author james todd [gonzo at jxta dot org]
 */

public class ProxyHttp
    extends JDialog {

    private static final String URL_DELIMITER = "://";
    private static final ResourceBundle STRINGS = Resources.getStrings();

    private JTextField httpProxy = null;
    private boolean isCancel = false;
    private JButton ok = null;

    /**
     * Create panel that collects the password to join the group
     */
    public ProxyHttp(MyJXTA myjxta) {
        super((MyJXTAView)myjxta.getView());
        
        MyJXTAView view = (MyJXTAView) myjxta.getView();
        
        setTitle(STRINGS.getString("label.config.proxy.http"));
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setLocationRelativeTo(view);
        // xxx: jre 1.5
        //setAlwaysOnTop(false);
        
        getContentPane().add(ui());
        pack();
        setVisible(true);
    }

    public URL getHttpProxy() {
        return toURL(this.httpProxy.getText());
    }

    /**
     * Build the ui of the panel 
     */
    private JPanel ui() {
        JPanel p = new JPanel();
        GridBagLayout gb = new GridBagLayout();
        GridBagConstraints gbc = new GridBagConstraints();

        p.setLayout(gb);
        p.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3));

        JLabel l = new JLabel(STRINGS.getString("label.config.proxy.http"));

        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 1;
        gbc.gridheight = 1;
        gbc.weightx = 1.0;
        gbc.weighty = 1.0;
        gbc.anchor = GridBagConstraints.FIRST_LINE_START;
        gbc.fill = GridBagConstraints.BOTH;
        gbc.insets = new Insets(3, 3, 3, 3);
        gbc.ipadx = 0;
        gbc.ipady = 0;

        gb.setConstraints(l, gbc);

        p.add(l);

        this.httpProxy = new JTextField(15);
        
        this.httpProxy.setText(Constants.getInstance().get(Constants.PROXY_HTTP));
        this.httpProxy.addKeyListener(new KeyAdapter() {
            public void keyReleased(KeyEvent ke) {
                ok.setEnabled(isValidInput());
            }
        });

        gbc.gridx++;
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        gbc.fill = GridBagConstraints.BOTH;

        gb.setConstraints(this.httpProxy, gbc);

        p.add(this.httpProxy);

        JPanel bp = new JPanel();
        
        bp.setLayout(new GridLayout(1, 0));
        
        this.ok = new JButton(new AbstractAction() {
            public void actionPerformed(ActionEvent ae) {
                if (isValidInput()) {
                    exit();
                }
            }
        });

        this.ok.setText(STRINGS.getString("action.ok"));
        this.ok.addKeyListener(new AbstractButtonKeyListener(this.ok) {
            public void keyReleased(KeyEvent ke) {
                getButton().getAction().actionPerformed(null);
            }
        });
        this.ok.setEnabled(isValidInput());

        bp.add(this.ok);

        JButton b = new JButton(new AbstractAction() {
            public void actionPerformed(ActionEvent ae) {
                isCancel = true;
                exit();
            }
        });

        b.setText(STRINGS.getString("action.cancel"));
        b.addKeyListener(new AbstractButtonKeyListener(b) {
            public void keyReleased(KeyEvent ke) {
                getButton().getAction().actionPerformed(null);
            }
        });

        bp.add(b);
        
        gbc.gridx = 0;
        gbc.gridy++;
        gbc.gridwidth = 2;
        gbc.anchor = GridBagConstraints.LAST_LINE_END;
        gbc.fill = GridBagConstraints.NONE;

        gb.setConstraints(bp, gbc);

        p.add(bp);

//        getRootPane().setDefaultButton(this.ok);
        
        return p;
    }

    private void exit() {
        if (! this.isCancel) {
            URL hp = getHttpProxy();
            Constants c = Constants.getInstance();
            
            c.set(Constants.PROXY_HTTP, hp != null ? hp.toString() : "");
            c.save();
    
            System.setProperty(Env.HTTP_PROXY_HOST,
                hp != null ? hp.getHost() : "");
            System.setProperty(Env.HTTP_PROXY_PORT,
                hp != null ? String.valueOf(hp.getPort()) : "");
        }
        
        getRootPane().getParent().setVisible(false);
    }

    /**
     * Validate user input and display a descriptive message
     * if the input is incorrect
     */
    private boolean isValidInput() {
        String pr = this.httpProxy.getText().trim();
        URL pu = toURL(pr);
        boolean isValid = pr.length() == 0 ||
            (pr.length() > 0 &&
                pu != null);
        
        if (pu != null) {
            this.httpProxy.setText(pu.toString());
        }

        if (! isValid) {
            validate();
        }

        return isValid;
    }
    
    private URL toURL(String s) {
        URL u = null;
        
        if (s != null &&
            s.trim().length() > 0) {
            try {
                u = new URL(s);
            } catch (MalformedURLException mue) {
            }
        
            if (u == null) {
                try {
                    u = new URL(Constants.PROTOCOL_HTTP + URL_DELIMITER + s);
                } catch (MalformedURLException mue) {
                }
            }
        }
        
        if (u != null &&
            u.getPort() == -1) {
            u = null;
        }
                
        return u;
    }
}
